package com.utooo.service.purchase;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.utooo.constant.ResultCodeConstant;
import com.utooo.dao.purchase.OrderReceiptDetailMapper;
import com.utooo.dao.purchase.OrderReceiptMapper;
import com.utooo.dao.purchase.OrderReturnDetailMapper;
import com.utooo.dao.purchase.OrderReturnMapper;
import com.utooo.dao.quality.InspectionTaskMapper;
import com.utooo.dao.supplier.SupplierOrderReturnMapper;
import com.utooo.pojo.domain.purchase.order.OrderReceiptDO;
import com.utooo.pojo.domain.purchase.order.OrderReceiptDetailDO;
import com.utooo.pojo.domain.purchase.order.OrderReturnDO;
import com.utooo.pojo.domain.purchase.order.OrderReturnDetailDO;
import com.utooo.pojo.domain.quality.InspectionTaskDO;
import com.utooo.pojo.domain.supplier.execute.SupplierOrderReturnDO;
import com.utooo.pojo.dto.common.RestResult;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.utooo.constant.Constans.IGNORED_PROPERTIES;

@Slf4j
@Service
public class OrderReturnServiceImpl extends ServiceImpl<OrderReturnMapper, OrderReturnDO>
        implements OrderReturnService {

    @Resource
    private OrderReceiptMapper orderReceiptMapper;
    @Resource
    private OrderReceiptDetailMapper orderReceiptDetailMapper;
    @Resource
    private OrderReturnDetailMapper orderReturnDetailMapper;
    @Resource
    private SupplierOrderReturnMapper supplierOrderReturnMapper;
    @Resource
    private InspectionTaskMapper inspectionTaskMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<String> addOrderReturn(String inspectionTaskId) {
        InspectionTaskDO inspectionTask = inspectionTaskMapper.selectById(inspectionTaskId);
        if (inspectionTask == null) {
            log.error("进货查验任务为空！, inspectionTaskId: {}", inspectionTaskId);
            return new RestResult<>(ResultCodeConstant.CODE_400, "该进货查验任务已入库！");
        }

        List<OrderReturnDO> orderReturns = this.list(new LambdaQueryWrapper<OrderReturnDO>()
                .eq(OrderReturnDO::getInspectionTaskId, inspectionTaskId));
        if (CollUtil.isNotEmpty(orderReturns)) {
            log.error("该进货查验任务已退货！, inspectionTaskId: {}", inspectionTaskId);
            return new RestResult<>(ResultCodeConstant.CODE_400, "该记录已操作，请勿重复操作！");
        }

        String receiptId = inspectionTask.getReceiptNo();
        OrderReceiptDO orderReceipt = orderReceiptMapper.selectOne(new LambdaQueryWrapper<OrderReceiptDO>()
                .eq(OrderReceiptDO::getId, receiptId));
        if (orderReceipt == null) {
            log.error("orderReceipt: {} not found", inspectionTaskId);
            return new RestResult<>(ResultCodeConstant.CODE_400, "收货不存在！");
        }
        String receiptDetailId = inspectionTask.getReceiptDetailId();
        OrderReceiptDetailDO orderReceiptDetail = orderReceiptDetailMapper
                .selectOne(new LambdaQueryWrapper<OrderReceiptDetailDO>()
                        .eq(OrderReceiptDetailDO::getId, receiptDetailId));
        if (orderReceiptDetail == null) {
            log.error("收货物料明细为空！: {}", receiptDetailId);
            return new RestResult<>(ResultCodeConstant.CODE_400, "收货物料明细为空！");
        }
        // 采购方订单退货
        String receiptNo = orderReceipt.getReceiptNo();
        OrderReturnDO orderReturnDO = new OrderReturnDO();
        BeanUtil.copyProperties(orderReceipt, orderReturnDO, IGNORED_PROPERTIES);
        orderReturnDO.setInspectionTaskId(inspectionTaskId);
        String returnNo = generateOrderReturnNo();
        orderReturnDO.setReturnNo(returnNo);
        orderReturnDO.setReceiptNo(receiptId);
        LocalDateTime returnDate = LocalDateTime.now();
        orderReturnDO.setReturnDate(returnDate);
        Integer quantity = inspectionTask.getQuantity();
        orderReturnDO.setTotalReturnQuantity(quantity);
        BigDecimal receivedAmountIncludingTax = orderReceipt.getReceivedAmountIncludingTax();
        orderReturnDO.setReturnAmountIncludingTax(receivedAmountIncludingTax);
        this.save(orderReturnDO);

        OrderReturnDetailDO orderReturnDetail = new OrderReturnDetailDO();
        BeanUtil.copyProperties(orderReceiptDetail, orderReturnDetail, IGNORED_PROPERTIES);
        orderReturnDetail.setOrderNoLine(orderReceiptDetail.getOrderNo());
        orderReturnDetail.setReceiptNoLine(receiptNo);
        orderReturnDetail.setForeignId(orderReturnDO.getId());
        orderReturnDetail.setQuantity(quantity);
        String company = inspectionTask.getCompany();
        orderReturnDetail.setCompany(company);
        orderReturnDetailMapper.insert(orderReturnDetail);;

        // 供应商门户采购订单退货
        SupplierOrderReturnDO supplierOrderReturnDO = new SupplierOrderReturnDO();
        BeanUtil.copyProperties(orderReceipt, supplierOrderReturnDO, IGNORED_PROPERTIES);
        supplierOrderReturnDO.setApprovalStatus("1");
        supplierOrderReturnDO.setReturnNo(returnNo);
        supplierOrderReturnDO.setReturnDate(returnDate);
        supplierOrderReturnDO.setTotalReturnQuantity(quantity);
        supplierOrderReturnDO.setReturnAmountIncludingTax(receivedAmountIncludingTax);
        supplierOrderReturnMapper.insert(supplierOrderReturnDO);
        String supplierOrderReturnId = supplierOrderReturnDO.getId();
        OrderReturnDetailDO supplierOrderReturnDetail = new OrderReturnDetailDO();
        BeanUtil.copyProperties(orderReceiptDetail, supplierOrderReturnDetail, IGNORED_PROPERTIES);
        supplierOrderReturnDetail.setOrderNoLine(orderReceiptDetail.getOrderNo());
        supplierOrderReturnDetail.setReceiptNoLine(receiptNo);
        supplierOrderReturnDetail.setForeignId(supplierOrderReturnId);
        supplierOrderReturnDetail.setQuantity(quantity);
        supplierOrderReturnDetail.setCompany(company);
        orderReturnDetailMapper.insert(supplierOrderReturnDetail);
        return new RestResult<>(ResultCodeConstant.CODE_200, ResultCodeConstant.CODE_200_MSG);
    }

    private String generateOrderReturnNo() {
        String prefix = "TH";
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        String datePart = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 查询当天已有的最大订单号
        LambdaQueryWrapper<OrderReturnDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.likeRight(OrderReturnDO::getReturnNo, prefix + datePart);
        queryWrapper.orderByDesc(OrderReturnDO::getReturnNo);
        queryWrapper.last("LIMIT 1");
        OrderReturnDO orderReturnDO = this.getOne(queryWrapper);

        // 生成序列号
        int maxSequence = 0;
        if (orderReturnDO != null) {
            String returnNo = orderReturnDO.getReturnNo();
            maxSequence = Integer.parseInt(returnNo.substring((prefix + datePart).length()));
        }
        int nextSequence = maxSequence + 1;
        String sequencePart = String.format("%03d", nextSequence);
        return prefix + datePart + sequencePart;
    }
}